#!/bin/bash
scripts_dir=$(pwd)
project_dir=${scripts_dir}/..
dist_dir=~/dist
dist_sub_dir=etta-m1
url=http://192.168.0.7:8090/source/dist.git

parse_dist_name() {
dist_name=$1
}

parse_branch_name() {
REMOTE=$(echo $1 | sed 's/\// /g' | awk '{printf $1}')
BRANCH=$(echo ${1#$REMOTE/})
}

parse_input_params() {
if [ $# -lt 2 ]; then
  echo "Usage: $0 <dist_name> <remote>/<branch>"
  exit 255
fi

parse_dist_name $1
parse_branch_name $2

echo $dist_name
echo $REMOTE
echo $BRANCH
}

upload() {
mkdir ${dist_dir} >/dev/null 2>&1
cd ${dist_dir}/

# create local repository
if [ ! -d ".git" ]; then
  git init
  git remote add -f ${REMOTE} ${url}
  git config core.sparsecheckout true
  echo ${dist_sub_dir} >> .git/info/sparse-checkout
fi

# fetch remote
git fetch ${REMOTE}

# pull remote branch to local
git rev-parse --verify ${BRANCH} >/dev/null 2>&1
if [ $? -eq 0 ]; then
  git checkout ${BRANCH}
  git pull ${REMOTE} ${BRANCH}
else
  git checkout -b ${BRANCH} ${REMOTE}/${BRANCH}
fi

# commit
mv ${project_dir}/${dist_name}.deb ${dist_dir}/${dist_sub_dir}/
if [ $? -eq 0 ]; then
  # local commit
  git add ${dist_dir}/${dist_sub_dir}/${dist_name}.deb
  git commit -m ${dist_name}

  # push local to remote
  git push ${REMOTE} ${BRANCH}
fi
}

parse_input_params $@
upload